﻿<template>
	<div class="store-materials-container" v-loading="state.exportLoading">
		<splitpanes class="default-theme">
			<!-- 左侧物资分类树 -->
			<pane size="15">
				<StoreTypeTree ref="storeTypeTreeRef" :data="state.storeTypeTreeData" @node-click="handleCategoryChange" @refresh="loadStoreTypeTree" />
			</pane>

			<!-- 右侧物资信息表格 -->
			<pane size="80" style="overflow: auto">
				<el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
					<el-form :model="state.tableQueryParams" ref="queryForm" labelWidth="90">
						<el-row>
							<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
								<el-form-item label="关键字">
									<el-input v-model="state.tableQueryParams.keyword" clearable placeholder="请输入模糊查询关键字" />
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
								<el-form-item label="物资名称">
									<el-input v-model="state.tableQueryParams.name" clearable placeholder="请输入物资名称" />
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
								<el-form-item label="状态">
									<g-sys-dict v-model="state.tableQueryParams.status" code="StatusEnum" render-as="select" placeholder="请选择状态" clearable filterable />
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
								<el-form-item label="库存状态">
									<g-sys-dict v-model="state.tableQueryParams.stockStatus" code="StockStatusEnum" render-as="select" placeholder="请选择库存状态" clearable filterable />
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
								<el-form-item>
									<el-button-group style="display: flex; align-items: center">
										<el-button type="primary" icon="ele-Search" @click="handleQuery" v-auth="'storeMaterials:page'" v-reclick="1000"> 查询 </el-button>
										<el-button icon="ele-Refresh" @click="resetQuery"> 重置 </el-button>
										<el-button icon="ele-ZoomIn" @click="() => (state.showAdvanceQueryUI = true)" v-if="!state.showAdvanceQueryUI" style="margin-left: 5px"> 高级查询 </el-button>
										<el-button icon="ele-ZoomOut" @click="() => (state.showAdvanceQueryUI = false)" v-if="state.showAdvanceQueryUI" style="margin-left: 5px"> 隐藏 </el-button>
										<el-button type="danger" style="margin-left: 5px" icon="ele-Delete" @click="batchDelStoreMaterials" :disabled="state.selectData.length == 0" v-auth="'storeMaterials:batchDelete'">
											删除
										</el-button>
										<el-button type="primary" style="margin-left: 5px" icon="ele-Plus" @click="editDialogRef.openDialog(null, '新增物资信息表')" v-auth="'storeMaterials:add'"> 新增 </el-button>
										<el-dropdown :show-timeout="70" :hide-timeout="50" @command="exportStoreMaterialsCommand">
											<el-button type="primary" style="margin-left: 5px" icon="ele-FolderOpened" v-reclick="20000" v-auth="'storeMaterials:export'"> 导出 </el-button>
											<template #dropdown>
												<el-dropdown-menu>
													<el-dropdown-item command="select" :disabled="state.selectData.length == 0">导出选中</el-dropdown-item>
													<el-dropdown-item command="current">导出本页</el-dropdown-item>
													<el-dropdown-item command="all">导出全部</el-dropdown-item>
												</el-dropdown-menu>
											</template>
										</el-dropdown>
										<el-button type="warning" style="margin-left: 5px" icon="ele-MostlyCloudy" @click="importDataRef.openDialog()" v-auth="'storeMaterials:import'"> 导入 </el-button>
									</el-button-group>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</el-card>

				<el-card class="full-table" shadow="hover" style="margin-top: 5px">
					<el-table
						:data="state.tableData"
						@selection-change="
							(val: any[]) => {
								state.selectData = val;
							}
						"
						style="width: 100%"
						v-loading="state.tableLoading"
						tooltip-effect="light"
						row-key="id"
						@sort-change="sortChange"
						border
					>
						<el-table-column type="selection" width="40" align="center" fixed="left" v-if="auth('storeMaterials:batchDelete') || auth('storeMaterials:export')" />
						<el-table-column type="index" label="序号" width="55" align="center" fixed="left" />
						<el-table-column prop="storeTypeId" label="分类" width="150" fixed="left" :formatter="(row: any) => row.storeTypeDisplayName" show-overflow-tooltip />
						<el-table-column prop="name" label="物资名称" width="200" fixed="left" show-overflow-tooltip />
						<el-table-column prop="unit" label="单位" show-overflow-tooltip />
						<el-table-column prop="price" label="单价" show-overflow-tooltip />
						<el-table-column prop="minStock" label="最小库存" show-overflow-tooltip />
						<el-table-column prop="maxStock" label="最大库存" show-overflow-tooltip />
						<el-table-column prop="orderNo" label="排序" sortable="custom" show-overflow-tooltip />
						<el-table-column prop="status" label="状态" v-auth="'storeMaterials:setStatus'" show-overflow-tooltip>
							<template #default="scope">
								<el-switch v-model="scope.row.status" :active-value="1" :inactive-value="2" size="small" @change="changeStoreMaterialsStatus(scope.row)" />
							</template>
						</el-table-column>
						<el-table-column prop="currentStock" label="库存数量" show-overflow-tooltip />
						<el-table-column prop="availableStock" label="可用库存" fixed="left" show-overflow-tooltip />
						<el-table-column prop="reservedStock" label="申请库存" show-overflow-tooltip />
						<el-table-column prop="inTransitStock" label="入库库存" show-overflow-tooltip />
						<el-table-column prop="stockStatus" label="库存状态" fixed="left" show-overflow-tooltip>
							<template #default="scope">
								<g-sys-dict v-model="scope.row.stockStatus" code="StockStatusEnum" />
							</template>
						</el-table-column>
						<el-table-column prop="lastStockUpdateTime" label="更新时间" show-overflow-tooltip />
						<el-table-column prop="remark" label="备注" show-overflow-tooltip />
						<el-table-column label="修改记录" width="100" align="center" show-overflow-tooltip>
							<template #default="scope">
								<ModifyRecord :data="scope.row" />
							</template>
						</el-table-column>
						<el-table-column label="操作" width="140" align="center" fixed="right" show-overflow-tooltip v-if="auth('storeMaterials:update') || auth('storeMaterials:delete')">
							<template #default="scope">
								<el-button icon="ele-Edit" size="small" text type="primary" @click="editDialogRef.openDialog(scope.row, '编辑物资信息表')" v-auth="'storeMaterials:update'"> 编辑 </el-button>
								<el-button icon="ele-Delete" size="small" text type="primary" @click="delStoreMaterials(scope.row)" v-auth="'storeMaterials:delete'"> 删除 </el-button>
							</template>
						</el-table-column>
					</el-table>

					<el-pagination
						v-model:currentPage="state.tableParams.page"
						v-model:page-size="state.tableParams.pageSize"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						layout="total, sizes, prev, pager, next, jumper"
						:page-sizes="[10, 20, 50, 100, 200, 500]"
						:total="state.tableParams.total"
						size="small"
						background
					/>
				</el-card>
			</pane>
		</splitpanes>

		<!-- 对话框组件 -->
		<ImportData ref="importDataRef" :import="storeMaterialsApi.importData" :download="storeMaterialsApi.downloadTemplate" v-auth="'storeMaterials:import'" @refresh="handleQuery" />
		<printDialog ref="printDialogRef" :title="'打印物资信息表'" @reloadTable="handleQuery" />
		<editDialog ref="editDialogRef" @reloadTable="handleQuery" />
	</div>
</template>

<script lang="ts" setup name="storeMaterials">
import { ref, reactive, onMounted, nextTick } from 'vue';
import { auth } from '/@/utils/authFunction';
import { ElMessageBox, ElMessage } from 'element-plus';
import { downloadStreamFile } from '/@/utils/download';
import { useStoreMaterialsApi } from '/@/api/store/storeMaterials';
import { Splitpanes, Pane } from 'splitpanes';
import 'splitpanes/dist/splitpanes.css';

// 组件导入
import StoreTypeTree from '/@/views/store/storeMaterials/component/storeTypeTree.vue';
import editDialog from '/@/views/store/storeMaterials/component/editDialog.vue';
import printDialog from '/@/views/system/print/component/hiprint/preview.vue';
import ModifyRecord from '/@/components/table/modifyRecord.vue';
import ImportData from '/@/components/table/importData.vue';

const storeMaterialsApi = useStoreMaterialsApi();
const printDialogRef = ref();
const editDialogRef = ref();
const importDataRef = ref();
const storeTypeTreeRef = ref();

const state = reactive({
	exportLoading: false,
	tableLoading: false,
	stores: {},
	showAdvanceQueryUI: false,
	dropdownData: {} as any,
	selectData: [] as any[],
	storeTypeTreeData: [] as any[], // 物资分类树数据
	currentCategoryId: 0, // 当前选中的分类ID，0表示全部
	tableQueryParams: {} as any,
	tableParams: {
		page: 1,
		pageSize: 20,
		total: 0,
		field: 'createTime',
		order: 'descending',
		descStr: 'descending',
	},
	tableData: [],
});

// 页面加载时
onMounted(async () => {
	await loadStoreTypeTree();
	await handleQuery();
});

// 加载物资分类树数据
const loadStoreTypeTree = async () => {
	try {
		const data = (await storeMaterialsApi.getDropdownData(true).then((res) => res.data.result)) ?? {};
		console.log('API返回数据:', data); // 调试信息
		// 修正数据结构：从result.pid中获取数据，而不是data.storeTypeId
		state.dropdownData.storeTypeId = data.pid || [];
		state.storeTypeTreeData = data.pid || [];
		console.log('树数据:', state.storeTypeTreeData); // 调试信息
	} catch (error) {
		console.error('加载物资分类树失败:', error);
		ElMessage.error('加载物资分类失败');
	}
};

// 分类节点点击事件
const handleCategoryChange = (node: any) => {
	const nodeId = node.id || node.value || 0; // 兼容不同的字段名
	state.currentCategoryId = nodeId;
	// 重置分页参数
	state.tableParams.page = 1;
	// 设置分类查询参数
	if (nodeId === 0 || nodeId === '0') {
		// 选择了"全部"，清除分类筛选
		delete state.tableQueryParams.storeTypeId;
	} else {
		// 选择了具体分类
		state.tableQueryParams.storeTypeId = nodeId;
	}
	handleQuery();
};

// 查询操作
const handleQuery = async (params: any = {}) => {
	state.tableLoading = true;
	try {
		state.tableParams = Object.assign(state.tableParams, params);
		const queryParams = Object.assign({}, state.tableQueryParams, state.tableParams);
		const result = await storeMaterialsApi.page(queryParams).then((res) => res.data.result);
		state.tableParams.total = result?.total;
		state.tableData = result?.items ?? [];
	} catch (error) {
		console.error('查询失败:', error);
		ElMessage.error('查询失败');
	} finally {
		state.tableLoading = false;
	}
};

// 重置查询
const resetQuery = () => {
	state.tableQueryParams = {};
	state.currentCategoryId = 0;
	// 重置树选择
	nextTick(() => {
		storeTypeTreeRef.value?.setCurrentKey(0);
	});
	handleQuery();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
	state.tableParams.pageSize = val;
	state.tableParams.page = 1;
	handleQuery();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
	state.tableParams.page = val;
	handleQuery();
};

// 列排序
const sortChange = async (column: any) => {
	state.tableParams.field = column.prop;
	state.tableParams.order = column.order;
	await handleQuery();
};

// 删除
const delStoreMaterials = (row: any) => {
	ElMessageBox.confirm(`确定要删除吗?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			await storeMaterialsApi.delete({ id: row.id });
			handleQuery();
			ElMessage.success('删除成功');
		})
		.catch(() => {});
};

// 批量删除
const batchDelStoreMaterials = () => {
	ElMessageBox.confirm(`确定要删除${state.selectData.length}条记录吗?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			await storeMaterialsApi.batchDelete(state.selectData.map((u) => ({ id: u.id }))).then((res) => {
				ElMessage.success(`成功批量删除${res.data.result}条记录`);
				handleQuery();
			});
		})
		.catch(() => {});
};

// 设置状态
const changeStoreMaterialsStatus = async (row: any) => {
	await storeMaterialsApi.setStatus({ id: row.id, status: row.status }).then(() => ElMessage.success('状态设置成功'));
};

// 导出数据
const exportStoreMaterialsCommand = async (command: string) => {
	try {
		state.exportLoading = true;
		let params;
		if (command === 'select') {
			params = Object.assign({}, state.tableQueryParams, state.tableParams, { selectKeyList: state.selectData.map((u) => u.id) });
		} else if (command === 'current') {
			params = Object.assign({}, state.tableQueryParams, state.tableParams);
		} else if (command === 'all') {
			params = Object.assign({}, state.tableQueryParams, state.tableParams, { page: 1, pageSize: 99999999 });
		}
		await storeMaterialsApi.exportData(params).then((res) => downloadStreamFile(res));
	} finally {
		state.exportLoading = false;
	}
};
</script>

<style scoped>
.store-materials-container {
	height: calc(100vh - 84px);
}

:deep(.el-input),
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}

:deep(.splitpanes__pane) {
	overflow: hidden;
}

:deep(.splitpanes__splitter) {
	background-color: var(--el-border-color-light);
	position: relative;
	opacity: 0.7;
}

:deep(.splitpanes__splitter:hover) {
	opacity: 1;
	background-color: var(--el-color-primary);
}
</style>
